<template>
  <div>
    <!-- 面包屑导航 -->
    <cate-breadcrumb />

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加分类按钮 -->
      <el-row class="mb15">
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-index="true"
        index-text="#"
        border
        :show-row-hover="false"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            v-if="!scope.row.cat_delete"
            class="el-icon-success"
            style="color: lightgreen"
          ></i>
          <i v-else class="el-icon-error" style="color: red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0" size="mini">一级</el-tag>
          <el-tag
            v-else-if="scope.row.cat_level === 1"
            type="success"
            size="mini"
            >二级</el-tag
          >
          <el-tag v-else type="warning" size="mini">三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCateInfo(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteCateInfo(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <!-- 添加分类表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称: " prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类: ">
          <el-cascader
            :options="parentCateList"
            :props="casecaderProps"
            v-model="selectedKeys"
            @change="parentCateChanged"
            clearable
            ref="cascaderRef"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑表单对话框 -->
    <el-dialog
      title="分类名称"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="editCateDialogClosed"
    >
      <el-form
        :model="editCateForm"
        :rules="editCateRules"
        ref="editCateFormRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cateName">
          <el-input v-model="editCateForm.cateName"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditedCate"> 确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CateBreadcrumb from './childComps/CateBreadcrumb'

import {
  getCateList,
  getParentCateList,
  addCate,
  getCateNameById,
  submitEditedCate,
  deleteCateInfoById,
} from 'network/cate.js'
export default {
  name: 'Cate',
  components: {
    CateBreadcrumb,
  },
  data() {
    return {
      cateList: [],
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok',
        },
        {
          label: '排序',
          type: 'template',
          template: 'order',
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt',
        },
      ],
      addCateDialogVisible: false,
      addCateForm: {
        cat_name: '',
        // 父类分类的id
        cat_pid: 0,
        // 默认添加一级分类
        cat_level: 0,
      },
      addCateRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },
      parentCateList: [],
      // 级联选择器的配置对象
      casecaderProps: {
        expandTrigger: 'hover',
        checkStrictly: true,
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      selectedKeys: [],
      editCateDialogVisible: false,
      editCateForm: {
        cateName: '',
      },
      editCateRules: {
        cateName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },
      cateId: '',
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const res = await getCateList(this.queryInfo)
      if (res.meta.status !== 200) return this.$message.error('获取商品失败!')
      this.cateList = res.data.result
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    showAddCateDialog() {
      this.getParentCateList(2)
      this.addCateDialogVisible = true
    },
    async getParentCateList(type) {
      const res = await getParentCateList(type)
      if (res.meta.status !== 200)
        return this.$message.error('获取父级数据失败!')
      this.parentCateList = res.data
    },
    parentCateChanged() {
      const length = this.selectedKeys.length
      if (length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[length - 1]
      } else {
        this.addCateForm.cat_pid = 0
      }
      this.addCateForm.cat_level = length
      //解决选择后关闭选择框
      this.$refs.cascaderRef.dropDownVisible = false
    },
    async addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return
        const res = await addCate(this.addCateForm)
        if (res.meta.status !== 201) return this.$message.error('添加分类失败!')
        this.$message.success('添加分类成功')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },
    addCateDialogClosed() {
      // 清空分类名称
      this.$refs.addCateFormRef.resetFields()
      // 清空级联选择
      this.selectedKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },
    editCateDialogClosed() {
      this.$refs.editCateFormRef.resetFields()
    },
    async editCateInfo(id) {
      this.cateId = id
      const res = await getCateNameById(id)
      if (res.meta.status !== 200) this.$message.error('获取分类名称失败!')
      this.editCateForm.cateName = res.data.cat_name
      this.editCateDialogVisible = true
    },
    async submitEditedCate() {
      this.$refs.editCateFormRef.validate(async (valid) => {
        if (!valid) return
        const res = await submitEditedCate(
          this.cateId,
          this.editCateForm.cateName
        )
        if (res.meta.status !== 200)
          return this.$message.error('修改分类名称失败!')
        this.$message.success('修改分类名称成功!')
        this.getCateList()
        this.editCateDialogVisible = false
      })
    },
    async deleteCateInfo(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消了删除')
      }

      const res = await deleteCateInfoById(id)
      if (res.meta.status !== 200) return this.$message.error('删除分类失败!')
      this.$message.success('删除分类成功!')
      this.getCateList()
    },
  },
}
</script>
<style lang="less">
.mb15 {
  margin-bottom: 15px;
}
// 去除单选框
.el-cascader-panel .el-radio {
  width: 100%;
  height: 100%;
  z-index: 10;
  position: absolute;
  top: 10px;
  right: 10px;
}

.el-cascader-panel .el-radio__input {
  visibility: hidden;
}

.el-cascader-panel .el-cascader-node__postfix {
  top: 10px;
}
</style>